﻿using System.Data.Entity;
using System.Linq;
using WSPay.Common.Data;

namespace WSPay.EF
{
    public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        internal DbContext Context;
        internal IDbSet<TEntity> DbSet;
        protected virtual void AttachIfNot(TEntity entity)
        {
            if (!DbSet.Local.Contains(entity))
            {
                DbSet.Attach(entity);
            }
        }
        public Repository(DbContext context)
        {
            Context = context;
            DbSet = context.Set<TEntity>();
        }
        public TEntity GetById(object id)
        {
            return DbSet.Find(id);
        }

        public void Update(TEntity entity)
        {
            //AttachIfNot(entity);
            //Context.Entry(entity).State = EntityState.Modified;
           DbSet.Attach(entity);
        }

        public void Delete(object id)
        {
            var entity = DbSet.Find(id);
            Delete(entity);
        }

        public void Delete(TEntity entity)
        {
            //DbSet.Attach(entity);
            AttachIfNot(entity);
            DbSet.Remove(entity);
        }

        public void Insert(TEntity entity)
        {
            DbSet.Add(entity);
        }

        public IQueryable<TEntity> Query()
        {
            return DbSet;
        }

        public IQueryable<TEntity> ReadQuery()
        {
            return DbSet.AsNoTracking();
        }

        public int Count(System.Linq.Expressions.Expression<System.Func<TEntity, bool>> predicate)
        {
            return DbSet.Count(predicate);
        }
    }
}
